from annoying.decorators import render_to
from django.http import Http404
from django.shortcuts import redirect, get_object_or_404

from core.extensions.decorators import login_required

from core.forms import EventForm
from core.models import Event, User
from core.views.event.details import details


@login_required()
@render_to('event/edit.html')
def edit(request, id):
    event = get_object_or_404(Event, id=id)
    user = User.objects.get(id=request.session['user_id'])
    if user != event.owner or event.status != Event.Status.Scheduled:
        raise Http404()
    if request.method == 'POST':
        form = EventForm(request.POST, request.FILES, instance=event)
        if form.is_valid():
            form.save()
            return redirect(details, id)
    else:
        form = EventForm(instance=event)
    return {'form': form, 'event': event}
